/**
 * 
 */
package com.cisetech.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.cisetech.util.JsonUtils;

/**
 * @author zhaopeng
 * @date Apr 20, 2015
 */
@Controller
public class BaseController {
	protected final static Logger log = LoggerFactory.getLogger(BaseController.class);
	/**
	 * 将 object 转成  json 并写入 response 
	 * @param response
	 * @param obj
	 */
	public void writeJSON(HttpServletResponse response,Object obj ){
		try {
			String strJSON = JsonUtils.obj2Json(obj);
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache, must-revalidate");
			response.setHeader("Pragma", "no-cache");
			response.getWriter().write(strJSON);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
			log.debug("------------------>>>>>>> format json  error ");
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("------------------>>>>>>> json  error ");
		}
	}
	
	@InitBinder
	protected void ininBinder(WebDataBinder binder){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf,true));
	}
}
